package org.simplextensions.registry.phaselisteners;

import javassist.bytecode.annotation.Annotation;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.simplextensions.annotations.ExtensionStyle;
import org.simplextensions.registry.Bundle;
import org.simplextensions.registry.EScanPhaseListener;
import org.simplextensions.registry.ExtensionPoint;
import org.simplextensions.registry.IExtensionRegistry;
import org.simplextensions.scanner.ScannHelper;

public class ExtensionPointScanPhaseListener extends EScanPhaseListener {

	private final static Log log = LogFactory.getLog(ExtensionPointScanPhaseListener.class);

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.simplextensions.scanner.IScanPhaseListener#scanClass(javassist
	 * .bytecode.ClassFile, javassist.bytecode.annotation.Annotation)
	 */
	public void scanClass(IExtensionRegistry extensionRegistry, Bundle bundle, String className, Annotation a) {
		scanAnnotation(extensionRegistry, bundle, a, className);
	}

	public void scanAnnotation(IExtensionRegistry extensionRegistry, Bundle bundle, Annotation a, String name) {
		log.trace("scanning extension point's class: " + name);

		String substring = name.substring(name.lastIndexOf(".") + 1);

		String smvId = ScannHelper.getStringValue(a, "id", substring + getSequenceValue(substring));
		Class<?>[] cmvEC = ScannHelper.getClassesValue(a, "extensionClass");
		String smvFM = ScannHelper.getStringValue(a, "factoryMethod");
		String[] smvsFM = ScannHelper.getStringsValue(a, "depends");
		ExtensionStyle emvStyle = (ExtensionStyle) ScannHelper.getEnumValue(a, "style");

			/*Class<?> forName = Class.forName(name);
			if (!IExtensionPoint.class.isAssignableFrom(forName)) {
				log.warn("extension point class: " + name + " does not implement interface: " + IExtensionPoint.class.getCanonicalName());
				return;
			}*/

			ExtensionPoint extensionPoint = new ExtensionPoint(extensionRegistry, bundle, name, smvId, cmvEC, emvStyle, smvFM);
			extensionPoint.setDepends(smvsFM);
			extensionRegistry.addExtensionPoint(extensionPoint);
	}

}